<?php
declare (strict_types = 1);

namespace app\admin\middleware;
use think\facade\Db;
use think\facade\Cookie;
use think\facade\Session;
use think\validate\ValidateRule;
use think\facade\View;



class UrlData
{
    use \liliuwei\think\Jump;
    public function handle($request, \Closure $next)
    {
        //侧边导航栏数据 中间件
        $user = $request->user;

        $where[] = ['n.node_grade','in','1,2'];

        if($user['admin_name'] != 'admin'){

        $where[] = ['a.id','=',$user['id']];
        $url = Db::table('admin')
                ->alias('a')
                ->join('admin_role a_r','a.id=a_r.admin_id')
                ->join('role_node r_n','r_n.role_id=a_r.role_id')
                ->join('node n','r_n.node_id=n.id')
                ->where($where)
                ->field('n.id,n.node_name,n.node_url,n.node_partent,n.node_grade')
                ->select()->toArray();

        }else{
            $url = Db::table('node')
                ->alias('n')
                ->where($where)
                ->field('n.id,n.node_name,n.node_url,n.node_partent,n.node_grade')
                ->select()
                ->toArray();
        }


        //分离1级节点和2级节点
        $grade_1 = [];
        $grade_2 = [];
        foreach ($url as $v){
            if($v['node_grade'] == 1){
                $grade_1[] = $v;
            }else{
                $grade_2[] = $v;
            }

        }

        foreach ($grade_1 as $key=>$val){       //对2级节点接入父节点子数组

            foreach ($grade_2 as $v){
                if($v['node_partent'] == $val['id']){
                    $grade_1[$key]['child'][] = $v;
                }
            }
        }


        View::assign('url',$grade_1);    //给控制器视图全局传值
        return $next($request);
    }
}
